package com.io.centinel;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.io.dto.BaseRes;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * The class/interface
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@Component
public class SentinelHandlerPage implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        BaseRes baseResponse = null;
        if (e instanceof FlowException) {
            baseResponse = new BaseRes(-1, "接口被限流");
        } else if (e instanceof DegradeException) {
            baseResponse = new BaseRes(-2, "接口被降级");
        }
        response.getWriter().write(JSONUtil.toJsonStr(baseResponse));
    }
}
